<template>
	<view class="goods-order" :class="themeName">
		<!-- 配送方式 -->
		<view class="contain delivery">
			<view class="delivery-tabs" v-if="deliveryTypeTabsList.length !== 1 && from != 4">
				<u-tabs :list="deliveryTypeTabsList" :is-scroll="false" :height="88" :active-color="themeColor"
					:bar-style="{ top: '100%' }" :bar-width="100" :current="deliveryTypeTabsIndex"
					@change="changeDeliveryType" />
			</view>

			<!-- 快递配送 -->
			<view class="delivery-contain" v-show="deliveryActive['sign'] === 'express'" @tap="onAddressSelect">
				<address-card :action="true" :has-content="JSON.stringify(addressInfo) !== '[]'">
					<template slot="header">
						<text>{{ addressInfo.contact }}</text>
						<text class="m-l-10">{{ addressInfo.mobile }}</text>
					</template>
					<template slot="main">
						<text>{{ addressInfo.province }}</text>
						<text class="m-l-10">{{ addressInfo.city }}</text>
						<text class="m-l-10">{{ addressInfo.district }}</text>
						<text class="m-l-10">{{ addressInfo.address }}</text>
					</template>
				</address-card>
			</view>

			<!-- 门店自提 -->
			<view class="delivery-contain" v-show="deliveryActive['sign'] === 'store'" @tap="onStoreSelect">
				<address-card :action="true" :has-content="!!orderForm.selffetch_shop_id"
					:placeholder="$zhTran('请选择门店地址')">
					<template slot="header">
						<text>{{ selffetchStoreInfo.name }}</text>
					</template>
					<template slot="main">
						<text>{{ selffetchStoreInfo.detailed_address }}</text>
					</template>
					<template slot="footer">
						<text>
							<text>{{ $zhTran('营业时间') }}：</text>
							<text>{{ selffetchStoreInfo.business_start_time }}</text>
							<text>-</text>
							<text>{{ selffetchStoreInfo.business_end_time }}</text>
						</text>
					</template>
				</address-card>
			</view>
		</view>

		<!-- 门店自提表单 -->
		<view class="contain store-from" v-show="deliveryActive['sign'] === 'store'">
			<view class="store-from-item">
				<text>{{ $zhTran('提货人') }}</text>
				<u-input v-model="orderForm.contact" class="flex-1" type="text" input-align="right"
					:placeholder="$zhTran('请输入提货人')" :clearable="false" />
			</view>
			<view class="store-from-item">
				<text>{{ $zhTran('联系方式') }}</text>
				<u-input v-model="orderForm.mobile" class="flex-1" type="text" input-align="right"
					:placeholder="$zhTran('请输入联系方式')" :clearable="false" />
			</view>
		</view>


		<!-- 订单商品 -->
		<view class="contain">
			<!-- 商品列表 -->
			<view class="goods">
				<view v-for="item in orderGoodsList" :key="item.id" class="goods-item">
					<goods-card shape="rectangle" :name="item.goods_name" :image="item.image"
						:contain-style="{ 'border-raius': 0, 'height': '290rpx' }"
						:image-style="{ 'width': '160rpx', 'height': '160rpx' }" :tag_desc="item.tag_desc">
						<view class="flex-1" slot="default">
							<!-- <view class="xs line-1" v-if="orderInfo.show_order_settle_goods_tag">
								<u-image width="80rpx" height="40rpx" :src="item.tag_desc" v-if="item.tag_desc != ''" />
							</view> -->
							<view class="gfa-tag" v-if="item.is_gifts">{{ $zhTran('赠品') }}</view>
							<text class="muted xs m-t-10">{{ item.spec_value_str }}</text>
							<text class="muted xs" v-if="item.coupon_unuse == 1">{{ $zhTran('(不可用优惠券)') }}</text>
							<view class="xs m-t-10" v-if="orderInfo.show_order_settle_goods_code" :style="{
								color: orderInfo.order_settle_goods_code_color
							}">{{ $zhTran('编码：') }}{{ item.code == null ? '' : item.code }}</view>
							<view class="xs m-t-10" v-if="orderInfo.show_order_settle_goods_model" :style="{
								color: orderInfo.order_settle_goods_model_color
							}">{{ $zhTran('型号：') }}{{ item.goods_model == null ? '' : item.goods_model }}</view>
							<view class="m-t-10 flex row-between">
								<view class="flex">
									<!-- 售价 -->
									<price :content="item.original_price" mainSize="32rpx" minorSize="24rpx"
										:prefix="orderInfo.price_symbol" />

									<!-- 普通商品或者虚拟商品会员价 用户有登陆且且该商品有设置会员价才显示 -->
									<view class="vip-price flex m-l-10"
										v-if="!!item.member_price && (orderInfo.order_type == 0 || orderInfo.order_type == 4)">
										<view class="price-name xxs">{{ $zhTran('会员价') }}</view>
										<view style="padding: 0 10rpx">
											<price :content="item.member_price || item.sell_price" :weight="500"
												color="#7B3200" :prefix="orderInfo.price_symbol">
											</price>
										</view>
									</view>
									<!-- 其他活动价 -->
									<view class="vip-price flex m-l-10"
										v-if="orderInfo.order_type == 1 || orderInfo.order_type == 2 || orderInfo.order_type == 3">
										<view class="price-name xxs" v-if="orderInfo.order_type == 1">
											{{ $zhTran('拼团价') }}
										</view>
										<view class="price-name xxs" v-if="orderInfo.order_type == 2">
											{{ $zhTran('秒杀价') }}
										</view>
										<view class="price-name xxs" v-if="orderInfo.order_type == 3">
											{{ $zhTran('砍价') }}
										</view>
										<view style="padding: 0 10rpx">
											<price :content="item.sell_price" :weight="500" color="#7B3200"
												:prefix="orderInfo.price_symbol">
											</price>
										</view>
									</view>
								</view>
								<view class="lighter sm flex">
									<view>x{{ item.goods_num }}</view>
									<!-- <view v-if="pageQueryPayload.source != 'buy_again'">x{{ item.goods_num }}</view> -->
									<!-- <u-number-box :disabled="item.cart_status != 0" v-model="item.goods_num"
										:min="item.min||1" :step="item.step||1" async-change positiveInteger :size="36"
										@change="countChange($event, item.id)" v-else/> -->
									<view v-if="Object.keys(item.aux_info).length > 0">
										{{item.unit_desc + '( ' + item.aux_info.goods_num + item.aux_info.aux_unit_name + ') '}}
									</view>
								</view>
							</view>
						</view>
					</goods-card>
					<!-- 商品小附件 -->
					<view class="goods-item-widget" v-if="from != 4">
						<view v-if="deliveryActive['sign'] === 'express' && !item.is_express" class="delivery-tag">
							{{ $zhTran('该商品不支持快递配送') }}
						</view>
						<view v-if="deliveryActive['sign'] === 'store' && !item.is_selffetch" class="delivery-tag">
							{{ $zhTran('该商品不支持门店自提') }}
						</view>
					</view>
				</view>
			</view>

			<!-- 买家留言 -->
			<view class="cell remark">
				<view class="cell-label">{{ $zhTran('买家留言') }}</view>
				<view class="cell-content">
					<u-input v-model="orderForm.user_remark" class="flex-1" type="text" :clearable="false"
						:maxlength="150" :placeholder="$zhTran('请添加备注（150字以内）')" />
				</view>
			</view>
		</view>

		<!-- 优惠 -->
		<view class="contain discounts" v-if="!isMarketing && !integrateFlag">
			<!-- 优惠券 -->
			<view class="cell discounts-item" @tap="showCoupons = true">
				<view class="cell-lable">{{ $zhTran('优惠券') }}</view>
				<view class="cell-content m-r-10" :style="{ color: themeColor }">{{ couponsActive.name || '' }}</view>
				<u-icon name="arrow-right" />
			</view>
		</view>

		<!-- 其他配送 -->
		<view class="contain discounts" v-if="other_express">
			<!-- 配送方式 -->
			<view class="cell discounts-item" @tap="showOtherExpress = true">
				<view class="cell-lable">{{ $zhTran('配送方式') }}</view>
				<view class="cell-content m-r-10">{{ orderForm.other_express_desc || $zhTran('快递发货') }}</view>
				<u-icon name="arrow-right" />
			</view>
		</view>

		<!-- 开具发票 -->
		<view class="contain discounts" v-if="orderInfo.invoice_enabled">
			<view class="cell discounts-item" @tap="showInvoicePop = true">
				<view class="cell-lable">{{ $zhTran('开具发票') }}</view>
				<view class="cell-content m-r-10">{{ invoice_desc }}</view>
				<u-icon name="arrow-right" />
			</view>
		</view>

		<view class="contain discounts" v-if="orderInfo.car_number_enabled">
			<view class="cell discounts-item" @click="showcarnum = true">
				<view class="cell-lable">{{ $zhTran('车牌号') }}</view>
				<view class="cell-content m-r-10">{{ orderForm.car_num }}</view>
				<u-icon name="arrow-right" />
			</view>
		</view>

		<view class="contain discounts"
			v-if="orderInfo.credit_show_way && orderInfo.credit_show_way.indexOf('place_order') > -1">
			<view class="cell discounts-item">
				<view class="cell-lable">{{ $zhTran('额度余额') }}</view>
				<view class="cell-content m-r-10">{{ userInfo.user_credit || 0 }}{{ userInfo.user_credit_unit || '' }}
				</view>
			</view>
		</view>

		<!-- 订单清算 -->
		<view class="contain clearing">
			<view class="cell clearing-item">
				<view class="cell-label">{{ $zhTran('商品金额') }}</view>
				<view class="cell-content">
					<price v-if="orderInfo.order_type == 0 || orderInfo.order_type == 4"
						:content="orderInfo.total_goods_original_price" :prefix="orderInfo.price_symbol" />
					<price v-else :content="orderInfo.total_goods_price" :prefix="orderInfo.price_symbol" />
				</view>
			</view>
			<view class="cell clearing-item">
				<view class="cell-label">{{
					orderInfo.stepwise_freight_nick != '' ? orderInfo.stepwise_freight_nick :
					$zhTran('运费')
				}}
				</view>
				<view class="cell-content">
					<price :content="orderInfo.express_price" :prefix="orderInfo.price_symbol" />
				</view>
			</view>
			<view class="cell clearing-item" v-if="!isMarketing && orderInfo.discount_amount > 0 && !integrateFlag">
				<view class="cell-label">{{ $zhTran('优惠券') }}</view>
				<view class="cell-content">
					<price :content="orderInfo.discount_amount" :prefix="'-' + orderInfo.price_symbol"
						:color="themeColor" />
				</view>
			</view>
			<view class="cell clearing-item" v-if="orderInfo.member_amount > 0">
				<view class="cell-label">{{ $zhTran('会员折扣') }}</view>
				<view class="cell-content">
					<price :content="orderInfo.member_amount" :color="themeColor" prefix="-￥" />
				</view>
			</view>
		</view>

		<view class="contain clearing" v-if="integrateFlag">
			<view class="cell clearing-item">
				<view class="cell-label ">{{ $zhTran('付款方式') }}</view>
			</view>
			<view class="payment-main">
				<view class="payway-container u-skeleton-fillet">
					<!-- Payway -->
					<u-radio-group v-model="payway" style="width: 100%;">
						<view class="payway">
							<view class="payway-item" v-for="(item, index) in paywayList" :key="item.id"
								@click="changePayway(item.pay_way, item.pay_enabled)">
								<u-image :src="item.icon" width="48" height="48" mode="scaleToFill" />
								<view class="payway-item-content">
									<text class="payway-item-content-name">{{ item.name }}</text>
									<text class="payway-item-content-tips">{{ item.extra }}</text>
								</view>
								<u-radio shape="circle" :name="item.pay_way" :active-color="themeColor"
									:disabled="(order_pay_way == 5 && item.pay_way != 2) || item.pay_enabled == 2" />
							</view>
						</view>
					</u-radio-group>
					<template v-if="!paywayList.length">
						<view class="payway-empty">{{ $zhTran('暂无支付方式') }}</view>
					</template>
					<view v-if="payway == 5" style="padding: 20rpx 0;">
						<u-input v-model="groupPay_balMoney" :placeholder="$zhTran('请输入余额支付金额')" type="digit"
							:clearable="true" :border="true" class="grouppay-bal-input"></u-input>
					</view>
				</view>
			</view>

		</view>

		<w-jishuzhichi />
		<!-- 订单操作 -->
		<view class="operational">
			<view class="order-amount">
				<text>{{ $zhTran('合计:') }}</text>
				<price :content="orderInfo.order_amount" mainSize="38rpx" minorSize="30rpx" :color="themeColor"
					:prefix="orderInfo.price_symbol" />
			</view>
			<view
				:class="['payment-submit', 'operational-button', 'u-skeleton-fillet', { 'payment-submit--disabled': loadingPay }]"
				v-if="integrateFlag" @tap="onSubmitOrder">
				<u-loading mode="circle" :show="loadingPay" />
				<text v-show="!loadingPay">{{ $zhTran('立即支付') }}</text>
			</view>
			<view :class="['operational-button', 'u-skeleton-fillet', { 'payment-submit--disabled': loadingPay }]"
				v-else @tap="onSubmitOrder">
				<u-loading mode="circle" :show="loadingPay" />
				<text v-show="!loadingPay">{{ $zhTran('提交订单') }}</text>
			</view>
		</view>


		<!-- 优惠券【弹窗】 -->
		<u-popup v-model="showCoupons" mode="bottom" border-radius="14" :closeable="false"
			:safe-area-inset-bottom="true" @open="openCouponsPopup" @close="closeCouponsPopup">
			<view class="coupons">
				<view class="coupons-header">
					<text>{{ $zhTran('优惠券') }}</text>
					<u-icon name="close" color="#666666" @tap="showCoupons = false" />
				</view>

				<view class="coupons-main">
					<view class="coupons-main__tabs">
						<u-tabs v-if="showCoupons" :list="couponTabsList" :is-scroll="false" :current="couponTabsIndex"
							:height="80" :active-color="themeColor" :bar-style="{ top: '100%' }" :bar-width="100"
							:show-bar="true" @change="index => couponTabsIndex = index" />
					</view>

					<view class="coupons-main__contain">
						<!-- 可用优惠券 -->
						<scroll-view :scroll-y="true" style="height: 700rpx;"
							v-show="couponsTabActive['sign'] === 'usable'">
							<view class="coupons-item" v-for="item in couponsInfo.can_use" :key="item.id">
								<coupon-card mode='radio' :name="item.name" :money="item.money"
									:condition="item.condition_tips" :conditionWay="item.condition_way_tips"
									:time="item.use_time_tips" :scene="item.goods_tips" :coupon-id="item.id"
									:checked.sync="item.checked" :prefix="orderInfo.price_symbol"
									:desc="{ title: item.fail_use_tips, content: item.fail_use_detail }"
									@change="changeCouponUse(item, $event)" />
							</view>
							<u-empty v-if="!couponsInfo.can_use.length" :text="$zhTran('暂无优惠券')"
								:src="$getImageUri('resource/image/shopapi/uniapp/empty/coupon_icon.png')"
								:icon-size="180" />
						</scroll-view>
						<!-- 不可用优惠券 -->
						<scroll-view :scroll-y="true" style="height: 700rpx;"
							v-show="couponsTabActive['sign'] === 'disabled'">
							<view class="coupons-item" v-for="item in couponsInfo.not_can_use" :key="item.id">
								<coupon-card mode='normal' :name="item.name" :money="item.money"
									:condition="item.condition_tips" :conditionWay="item.condition_way_tips"
									:time="item.use_time_tips" :scene="item.goods_tips" :coupon-id="item.id"
									:prefix="orderInfo.price_symbol"
									:desc="{ title: item.fail_use_tips, content: item.fail_use_detail }" />
							</view>
							<u-empty v-if="!couponsInfo.not_can_use.length" :text="$zhTran('暂无优惠券')"
								:src="$getImageUri('resource/image/shopapi/uniapp/empty/coupon_icon.png')"
								:icon-size="180" />
						</scroll-view>
					</view>
				</view>

				<view class="coupons-footer">
					<view class="coupons-footer-button" @tap="useCoupon">{{ $zhTran('确认') }}</view>
				</view>
			</view>
		</u-popup>

		<!-- 页面状态 -->
		<page-status :status="pageStatus">
			<template #error>
				<u-empty :text="pageErrorMsg" :src="$getImageUri('resource/image/shopapi/uniapp/empty/order.png')"
					:icon-size="280" />
			</template>
		</page-status>

		<!-- 其他配送选择 -->
		<u-select v-model="showOtherExpress" :confirm-color="themeColor" cancel-color="#999" @confirm="expressChange"
			:list="otherExpressData"></u-select>

		<!-- 车牌号修改组件 -->
		<u-popup v-model="showcarnum" :closeable="true" :maskCloseAble="false" mode="center" border-radius="14">
			<view class="p-24 bg-white" style="width: 70vw;">
				<view class="m-b-30 xl text-center">{{ $zhTran('修改车牌号') }}</view>
				<form @submit="changeCarConfirm">
					<u-form-item :label="$zhTran('新车牌号')" :labelWidth="130">
						<input style="height: 60rpx;" class="nr" :value="orderForm.car_num" name="carnum"
							:placeholder="$zhTran('请输入新的车牌号')">
						</input>
					</u-form-item>
					<button class="btn flex br60 row-center" form-type="submit">{{ $zhTran('确定') }}</button>
				</form>
			</view>
		</u-popup>

		<!-- 发票选择弹窗-->
		<u-popup id="popup" v-model="showInvoicePop" border-radius="20" mode="bottom" :closeable="true">
			<view class="pop-container">
				<view class="pop-header">{{ $zhTran("选择发票抬头") }} </view>
				<scroll-view style="height: 800rpx" :scroll-y="true" class="invoice-title-container">
					<u-radio-group @change="invoiceChange" class="m-t-20" style="width: 100%;"
						v-model="orderForm.invoice_id">
						<block v-for="(item, index) in titleList" :key="index">
							<view class="invoice-title-panel">
								<u-radio :key="index" :name="item.id" :activeColor="themeColor">
								</u-radio>
								<view class="container">
									<view class="upper-panel flex">
										<view class="title-name flex">
											<text>{{item.title}}</text>
											<view class="default-tag" v-if="item.is_def">{{$zhTran('默认')}}</view>
										</view>
										<view class="type-tag"
											:class="[item.title_type == 0 ? 'personal' : 'enterprise']">
											{{$zhTran(item.title_type_desc+ item.type_desc)}}
										</view>
									</view>
									<view class="main-panel flex">
										<view class="title-info">
											<text class="mailbox">{{$zhTran('联系邮箱') }} {{item.email||''}} </text>
											<text class="mobile"
												v-if="item.title_type == 0">{{ $zhTran('联系电话 ')+ (item.mobile||'') }}</text>
											<text class="mobile" v-else>{{ $zhTran('企业税号 ')+item.duty_num}}</text>
										</view>
										<view class="btn edit" @click.stop="invoiceTitleEdit(item.id)">
											{{$zhTran('编辑')}}
										</view>
									</view>
								</view>
							</view>
						</block>
					</u-radio-group>
				</scroll-view>
				<view class="footer-panel">
					<view class="btn save" :style="{ backgroundColor: themeColor }" @click="addNewTitle">
						{{ $zhTran("添加新抬头") }}
					</view>
					<view class="btn cancel" :style="{ borderColor: themeColor, color: themeColor }"
						@click="unUseInvoice">{{ $zhTran("不使用发票") }}</view>
				</view>
			</view>
		</u-popup>

		<!-- 失效商品-->
		<u-popup v-model="showInvalidGoods" border-radius="20" mode="center" width="80%" :mask-close-able="false">
			<view class="invalid-container" :style="[bgStyle]">
				<view class="pop-header bold">{{ $zhTran("当前订单中存在库存不足的商品") }} </view>
				<view class="p-20">
					<view v-for="item,idx in goods_disabled" :key="idx" v-if="idx < 2">

						<view class="flex bg-white p-20 m-b-20 br10">
							<u-image width="160rpx" height="160rpx" :src="item.image" />
							<view class="m-l-20" style="flex: 1">
								<view class="line-2 nr">{{ item.goods_name }}</view>
								<view class="muted xs line-1 m-t-10">
									{{ item.spec_value_str }}
								</view>
								<view class="row-between flex m-t-20">
									<view class="price flex primary">
										<price :content="item.original_price" mainSize="32rpx" minorSize="24rpx"
											:prefix="orderInfo.price_symbol" />
									</view>
									<view class="cartNum">
										x {{item.goods_num}}
										<view v-if="Object.keys(item.aux_info).length > 0">
											{{item.unit_desc + '( ' + item.aux_info.goods_num + item.aux_info.aux_unit_name + ') '}}
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="flex row-center m-b-20">
					{{$zhTran('共'+goods_disabled.length+'件商品')}}
				</view>
				<view class="footer-panel">
					<view class="btn save flex row-center" @click="toCart">
						{{ $zhTran("购物车中查看") }}
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	/**
	 * @description 订单结算页
	 * @query { Number | OrderTypeEnum } from 订单类型: 0-商品；1-拼团；2-秒杀；3-砍价；4- 虚拟商品。
	 * @query { Object } payload 请求数据参数
	 * @example { from: OrderTypeEnum['GOODS'], payload: {source: 'buy_now', goods: {goods_num: 1, item_id: 24} }}
	 */

	import {
		mapActions
	} from 'vuex'
	import {
		apiOrderPlace,
		apiDeliveryType
	} from '@/api/order'
	import {
		apiSeckillPlace
	} from '@/api/activity'
	import {
		apiGoodsTeamPlace
	} from '@/api/goods'
	import {
		apiBargainSettle
	} from '@/api/bargain'
	import {
		apiCouponGoods
	} from '@/api/store'
	import {
		apiSubscribe,
		apiQuicklyPayStatus,
		apiQuicklyPayway,
		apiQuicklyPay
	} from '@/api/app'
	import {
		handleClientEvent
	} from '@/utils/tools'
	import {
		PageStatusEnum,
		OrderTypeEnum,
		OrderSourceEnum,
		PaymentStatusEnum,
		PayWayEnum,
		ClientEnum
	} from '@/utils/enum'
	import {
		wxpay,
		alipay,
		ttpay,
		tonglianpay,
		houlianpay,
		eeasypay
	} from '@/utils/pay'
	import Cache from '@/utils/cache'
	import {
		apiMnpAuthPay,
	} from "@/api/user";
	import {
		getCode,
	} from "@/utils/login";
	import {
		apiUserIncoiceLists
	} from "@/api/invoice"

	export default {
		name: 'GoodsOrder',

		data() {
			return {
				from: '', // 来源页面: 0-商品；1-拼团；2-秒杀；3-砍价。
				// 页面状态
				pageStatus: PageStatusEnum['LOADING'],
				pageErrorMsg: '', // 页面异常信息

				// 配送方式Tabs列表
				deliveryTypeTabsList: [{
					id: 1,
					name: this.$zhTran('快递配送'),
					sign: 'express',
				}, {
					id: 2,
					name: this.$zhTran('门店自提'),
					sign: 'store'
				}],
				deliveryTypeTabsIndex: 0, // 配送方式Tabs索引

				pageQueryPayload: {}, // 承载页面参数
				// 订单表单
				orderForm: {
					delivery_type: '', // 配送方式: 1-快递发货; 2-门店自提;
					user_remark: '', // 用户备注
					coupon_list_id: '', // 优惠券ID
					address_id: '', // 地址ID 【快递发货】
					selffetch_shop_id: '', // 自提门店ID 【门店自提】
					contact: '', // 提货人 【门店自提】
					mobile: '', // 联系电话 【门店自提】
					other_express_desc: '',
					other_express: 0, // 其他配送方式: 1-快递发货; 2-物流发货;
					car_num: '',
					invoice_id: ''
				},

				/** S 优惠券 **/
				showCoupons: false, // 优惠券: 显示|隐藏【弹窗】
				// 优惠券Tabs列表
				couponTabsList: [{
					sign: 'usable',
					name: this.$zhTran('可使用优惠券'),
				}, {
					sign: 'disabled',
					name: this.$zhTran('不可使用优惠券'),
				}],
				couponTabsIndex: 0, // 优惠券Tabs索引
				// 优惠券信息
				couponsInfo: {
					can_use: [],
					not_can_use: [],
				},
				couponsActive: {}, // 当前使用优惠券
				/** E 优惠券 **/

				addressInfo: {}, // 地址信息
				selffetchStoreInfo: {}, // 自提门店信息
				orderInfo: {}, // 订单信息
				orderGoodsList: [], // 订单商品
				other_express: 0, //1:开启其他配送选择
				showOtherExpress: false, // 其他配送: 显示|隐藏【弹窗】
				otherExpressData: [{
						label: this.$zhTran('快递发货'),
						children: [],
						pid: 0,
						value: 0
					},
					{
						label: this.$zhTran('物流发货'),
						children: [],
						pid: 0,
						value: 1
					},
				],
				payway: "",
				paywayList: [],
				loadingPay: false,
				groupPay_balMoney: "",
				old_order_id: "",
				new_order_id: "",
				eventChannel: null,
				options: {},
				showcarnum: false,
				pay_appid: '',
				payOpenWays: [
					PayWayEnum['WECHAT'],
					PayWayEnum['WALLET_WECHAT'],
					PayWayEnum['RCB_WECHAT'],
					PayWayEnum['KINGDEE_WECHAT'],
					PayWayEnum['KINGDEE_ALIPAY'],
					PayWayEnum['TONG_LIAN_PAY'],
					PayWayEnum['E_EASY_PAY'],
					PayWayEnum['HOU_LIAN_PAY'],
				],
				titleList: [],
				showInvoicePop: false,
				invoice_title_id: '',
				timer: null,
				goods_disabled: [],
				showInvalidGoods: false,
			}
		},

		computed: {
			// 过滤订单表单冗余参数
			orderFormParams() {
				const form = {
					...this.orderForm
				}

				// 根据物流方式过滤
				switch (form.delivery_type) {
					case 1:
						delete form.selffetch_shop_id
						delete form.contact
						delete form.mobile
						break;
					case 2:
						delete form.address_id
						break;
				}

				return form
			},

			// 根据订单类型扩展订单参数
			orderExtendParams() {
				const params = new Object()

				switch (this.from) {
					// 普通商品
					case OrderTypeEnum['GOODS']:
						break
						// 拼团商品
					case OrderTypeEnum['TEAM']:
						params.source = OrderSourceEnum['BUY_NOW']
						break
						// 秒杀商品
					case OrderTypeEnum['SECKILL']:
						params.source = OrderSourceEnum['BUY_NOW']
						break
						// 砍价商品
					case OrderTypeEnum['BARGAIN']:
						params.source = OrderSourceEnum['BUY_NOW']
						break
				}

				return {
					...params,
					clsp_id: Cache.get('clsp_id'),
					order_type: this.from
				}
			},

			// 是否营销商品
			isMarketing() {
				switch (this.from) {
					// 普通商品
					case OrderTypeEnum['VIRTUAL']:
					case OrderTypeEnum['GOODS']:
						return false
					default:
						return true
				}
			},
			integrateFlag() {
				return this.orderInfo.integrate_orders == 1
			},

			// 当前配送方式Tab
			deliveryActive() {
				return this.deliveryTypeTabsList[this.deliveryTypeTabsIndex]
			},

			// 当前优惠券Tab
			couponsTabActive() {
				return this.couponTabsList[this.couponTabsIndex]
			},

			// 当前发票类型
			invoice_desc() {
				const res = this.titleList.filter(item => item.id == this.orderForm.invoice_id)
				let type_text = ''
				if (res.length > 0) {
					type_text = this.$zhTran(res[0].title_type_desc + res[0].type_desc)
				} else {
					type_text = this.$zhTran('不使用发票')
				}
				return type_text
			},
			bgStyle() {
				return {
					'background-image': `url(${this.$getImageUri('resource/image/shopapi/uniapp/invalid-alert-bg.png')})`,
					'background-size': '100% 100%',
					'background-repeat': 'no-repeat',
				}
			}
		},

		methods: {
			...mapActions(['getUser']),
			// 初始化配送方式
			initDeliveryType() {
				return new Promise((resolve, reject) => {
					apiDeliveryType()
						.then(data => {
							const {
								is_express,
								is_selffetch,
								other_express
							} = data
							// 订单配送方式ID组
							const deliveries = []
							// 计入配送方式列表ID组
							is_express && deliveries.push(1)
							is_selffetch && deliveries.push(2)
							// 过滤配送方式
							this.deliveryTypeTabsList = this.deliveryTypeTabsList
								.filter(item => deliveries.includes(item['id']))
							// 初始化订单表单的配送方式
							this.orderForm.delivery_type = this.deliveryActive['id']
							this.other_express = other_express
							resolve(data)
						})
						.catch(errMsg => reject(errMsg ?? this.$zhTran('获取不到配送方式')))
				})
			},
			initPageData() {
				return new Promise((resolve, reject) => {
					apiQuicklyPayway({
						from: this.from
					}).then(data => {
						this.paywayList = this.$zhTran(data.lists)
						this.paywayList.forEach(item => {
							if (item.pay_enabled == 1) {
								this.payway = item.pay_way
								return true
							}
						})
						resolve(data)
					}).catch(errMsg => reject(errMsg))
				})
			},
			changePayway(value, pay_enabled) {
				if (!(this.order_pay_way == 5 && value != 2) && pay_enabled == 1)
					this.$set(this, 'payway', value)
			},

			// 其他配送选择
			expressChange(row) {
				this.orderForm.other_express = row[0].value
				this.orderForm.other_express_desc = row[0].label
				// console.log(this.orderForm)
			},

			// 修改车牌号
			async changeCarConfirm(e) {
				this.orderForm.car_num = e.detail.value.carnum
				this.showcarnum = false;
			},

			// 根据商品类型初始化订单数据
			initOrderData() {
				return new Promise((resolve, reject) => {
					apiOrderPlace({
						...this.orderFormParams,
						...this.pageQueryPayload,
						...this.orderExtendParams,
						rr_share_id: this.options.rr_share_id || '',
						rra_id: this.options.rra_id || '',
						action: 'settle',
					}).then(ndata => {
						let data = this.$zhTran(ndata)
						this.addressInfo = data.address
						this.orderForm.address_id = data.address?.id
						this.orderGoodsList = data.goods
						this.orderInfo = data
						this.orderForm.contact = data.selffetch_info.contact
						this.orderForm.mobile = data.selffetch_info.mobile
						this.getUser()
						resolve(data)
					}).catch(errMsg => reject(errMsg))
				})
			},

			/** S 优惠券 **/
			// 初始化优惠券列表
			initCouponGoods() {
				return new Promise((resolve, reject) => {
					let params = null
					const {
						goods,
						cart_id,
						source,
						again_order
					} = this.pageQueryPayload

					// buy_now | cart 处理：请求优惠券列表的参数处理
					switch (source) {
						case OrderSourceEnum['BUY_NOW']:
							const goodsItems = goods.map(item => ({
								num: item.goods_num,
								item_id: item.item_id,
							}))
							params = {
								goods: goodsItems,
								source: 1
							}
							break
						case OrderSourceEnum['CART']:
							params = {
								cart_ids: [...cart_id],
								source: 2
							}
							break
						case OrderSourceEnum['BUY_AGAIN']:
							params = {
								again_order,
								source: 3
							}
							break
					}

					apiCouponGoods({
						...params
					}).then(data => {
						data.can_use.forEach(item => item.checked = false)
						return data
					}).then(ndata => {
						let data = this.$zhTran(ndata)
						this.couponsActive = data.can_use.length == 0 || this.orderInfo.coupon_list_id ==
							0 ? {} : data.can_use.find(item => item.id == this.orderInfo.coupon_list_id)

						this.couponsInfo = data
						// Tab名称处理（优惠券数量）
						this.couponTabsList.forEach(item => {
							switch (item.sign) {
								case 'usable':
									item.name = item.name + `(${data.can_use_count})`
									break
								case 'disabled':
									item.name = item.name + `(${data.not_can_use_count})`
									break
							}
						})
						resolve(data)
					}).catch(errMsg => reject(errMsg))
				})
			},

			// 更改优惠券
			changeCouponUse(coupon, value) {
				this.couponsInfo.can_use.forEach(item => item.checked = false)
				coupon && (coupon.checked = true)
			},

			// 使用优惠券
			useCoupon() {
				this.showCoupons = false
				const coupon = this.couponsInfo.can_use.find(item => item.checked)
				this.couponsActive = coupon || {}
				this.$set(this.orderForm, 'coupon_list_id', coupon?.id || -1)
				this.initOrderData()
			},

			// 打开优惠券弹窗
			openCouponsPopup() {
				if (Object.keys(this.couponsActive).length) {
					const coupon = this.couponsInfo.can_use.find(item => item.id === this.couponsActive.id)
					coupon.checked = true
				}
			},

			// 关闭优惠券弹窗
			closeCouponsPopup() {
				if (!Object.keys(this.couponsActive).length) {
					this.couponsInfo.can_use.forEach(item => item.checked = false)
				}
			},
			/** E 优惠券 **/


			// 更改配送方式
			changeDeliveryType(index) {
				this.deliveryTypeTabsIndex = index
				this.orderForm.delivery_type = this.deliveryActive['id'];

				this.initOrderData()
			},

			// 点击地址选择
			onAddressSelect() {
				// 监听全局selectaddress事件
				if (this.orderInfo.integrate_orders == 1 && Object.keys(this.addressInfo).length > 0) {
					uni.showModal({
						content: this.$zhTran('系统已开启合单功能，不能修改收货地址'),
						showCancel: false,
					})
					return false
				}

				uni.$once('changeAddress', (id = this.orderForm.address_id) => {
					id && (this.orderForm.address_id = id)
					this.initOrderData()
				})

				this.$Router.push({
					path: '/bundle2/pages/address/address',
					query: {
						type: true
					}
				})
			},

			// 点击店铺选择
			onStoreSelect() {
				// 监听全局selectaddress事件
				uni.$once('changeStore', store => {
					this.selffetchStoreInfo = store
					this.orderForm.selffetch_shop_id = store.id
					this.initOrderData()
				})

				this.$Router.push({
					path: '/bundle/pages/store_list/store_list',
				})
			},

			// 点击提交订单
			onSubmitOrder() {
				uni.showModal({
					title: this.$zhTran('温馨提示'),
					content: this.$zhTran('是否确认下单?'),
					confirmColor: this.themeColor,
					success: async ({
						confirm
					}) => {
						try {
							if (!confirm) throw this.$zhTran('订单取消')

							// 微信订阅消息
							try {
								// #ifdef MP-WEIXIN
								await this.handleSubscribeMP_WEIXIN()
								// #endif
							} catch (errMsg) {
								console.log('SUBSCRIBE_ERROR_MSG:', errMsg)
							}

							// 下单处理
							!this.integrateFlag && this.handlePlaceOrder()
							this.integrateFlag && this.handlePrepay()
						} catch (errMsg) {
							console.log('ORDER_ERROR_MSG:', errMsg)
						}
					}
				});
			},

			// 预支付处理
			async handlePrepay() {
				// if (this.userInfo.is_auth === 0 && this.payOpenWays.indexOf(this.payway) > -1) {
				// 	uni.showModal({
				// 		content: this.$zhTran('当前账号未微信授权，请前往个人设置授权'),
				// 		confirmColor: this.themeColor,
				// 		confirmText: this.$zhTran('前往授权'),
				// 		success: ({
				// 			confirm
				// 		}) => {
				// 			if (confirm) {
				// 				this.$Router.push({
				// 					path: '/bundle/pages/user_profile/user_profile',
				// 					query: {
				// 						form: 'payment'
				// 					}
				// 				})
				// 			}
				// 		}
				// 	})
				// 	return
				// }
				// 阻止重复操作
				if (this.loadingPay) return
				this.loadingPay = true

				var groupPay_balMoney = this.groupPay_balMoney
				if (this.payway == 5) {
					if (groupPay_balMoney == '' || groupPay_balMoney == 0)
						this.payway = 2

					if (parseFloat(groupPay_balMoney) >= parseFloat(this.amount))
						this.payway = 1
				}

				let pay_openid = ''
				// #ifdef MP-WEIXIN
				switch (+this.payway) {
					case PayWayEnum['WECHAT']:
					case PayWayEnum['WALLET_WECHAT']:
					case PayWayEnum['RCB_WECHAT']:
					case PayWayEnum['KINGDEE_WECHAT']:
					case PayWayEnum['E_EASY_PAY']:
					case PayWayEnum['HOU_LIAN_PAY']:
						const code = await getCode();
						await apiMnpAuthPay({
							code,
						}).then((res) => {
							pay_openid = res.openid
						});
						break
					case PayWayEnum['TOUTIAO']:
						break
					case PayWayEnum['CASH_DELIVERY']:
						break
					case PayWayEnum['TONG_LIAN_PAY']:
						break
				}
				// #endif


				if (this.payway == PayWayEnum['KINGDEE_ALIPAY']) {

					// 处理：支付
					apiPrepay({
						from: "order",
						pay_way: this.payway,
						order_id: this.new_order_id,
						old_order_id: this.old_order_id,
						groupPay_balMoney: "" == this.groupPay_balMoney ? 0 : this.groupPay_balMoney,
						pay_openid,
						...this.orderFormParams,
						...this.pageQueryPayload,
						...this.orderExtendParams,
						rr_share_id: this.options.rr_share_id || '',
						rra_id: this.options.rra_id || '',
						action: 'buy',
					}).then(async ({
						config,
						pay_way,
						order_id,
						old_order_id,
						one_year_pass,
						terminal
					}) => {
						this.new_order_id = order_id
						this.old_order_id = old_order_id
						this.kingdeeAlipayShow = true
						this.kingdeeAlipayCodeUrl = config.codeUrl
						this.kingdeeAlipayContent = "复制支付链接至浏览器打开<br>" + this.kingdeeAlipayCodeUrl
					}).finally(() => {
						this.loadingPay = false
					})
				} else {
					// 处理：支付
					apiQuicklyPay({
						from: "order",
						pay_way: this.payway,
						order_id: this.new_order_id,
						old_order_id: this.old_order_id,
						groupPay_balMoney: "" == this.groupPay_balMoney ? 0 : this.groupPay_balMoney,
						pay_openid,
						...this.orderFormParams,
						...this.pageQueryPayload,
						...this.orderExtendParams,
						rr_share_id: this.options.rr_share_id || '',
						rra_id: this.options.rra_id || '',
						action: 'buy',
					}).then(async ({
						config,
						pay_way,
						order_id,
						old_order_id,
						one_year_pass,
						terminal,
						goods_disabled
					}) => {
						if (goods_disabled != undefined && goods_disabled.length > 0) {
							this.goods_disabled = goods_disabled
							this.showInvalidGoods = true
							resolve(order_id)
						} else {
							this.new_order_id = order_id
							this.old_order_id = old_order_id
							console.log('pay_way', pay_way)
							switch (+pay_way) {
								case PayWayEnum['WALLET']:
									await this.handleWalletPay()
									break
								case PayWayEnum['WECHAT']:
								case PayWayEnum['WALLET_WECHAT']:
								case PayWayEnum['RCB_WECHAT']:
								case PayWayEnum['KINGDEE_WECHAT']:
									await this.handleWechatPay(config)
									break
								case PayWayEnum['ALIPAY']:
								case PayWayEnum['KINGDEE_ALIPAY']:
									await this.handleAlipayPay(config)
									break
								case PayWayEnum['TOUTIAO']:
									await this.handleTtPay(config)
									break
								case PayWayEnum['CASH_DELIVERY']:
									await this.handlePayResult(PaymentStatusEnum['SUCCESS'])
									break
								case PayWayEnum['TONG_LIAN_PAY']:
									if (one_year_pass == 0 || terminal == ClientEnum['OA_WEIXIN']) {
										//未满一年，调用收银宝
										this.pay_appid = config.pay_appId
										await this.handleTongLianPay(config)
									} else {
										await this.handleWechatPay(config)
									}
									break
								case PayWayEnum['E_EASY_PAY']:
									if (one_year_pass == 0 || terminal == ClientEnum['OA_WEIXIN']) {
										//未满一年，调用收银宝
										this.pay_appid = config.pay_appId
										await this.handleEEasyPay(config)
									} else {
										await this.handleWechatPay(config)
									}
									break
								case PayWayEnum['HOU_LIAN_PAY']:
									this.pay_appid = config.pay_appId
									await this.handleHouLianPay(config)
									break
								default:
									throw this.$zhTran('支付异常')
							}
						}
					}).then(() => {
						this.handlePayResult({
							result: PaymentStatusEnum['SUCCESS'],
							order_id: this.old_order_id
						});
					}).catch(errMsg => {
						this.handlePayResult(PaymentStatusEnum['FAIL'])
						console.log('PAYMENT_ERROR_MSG:', errMsg)
					}).finally(() => {
						this.loadingPay = false
					})
				}
			},

			// 微信支付
			handleWechatPay(data) {
				return new Promise((resolve, reject) => {
					wxpay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},

			// 支付宝支付
			handleAlipayPay(data) {
				return new Promise((resolve, reject) => {
					alipay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},
			handleKingdeeAlipayPay() {
				this.queryPayResult().then(result => {
					result ?
						this.handlePayResult({
							result: PaymentStatusEnum['SUCCESS'],
							order_id: this.old_order_id
						}) : this.handlePayResult(PaymentStatusEnum['FAIL'])
				}).catch(errMsg => this.handlePayResult(errMsg))
			},

			// 钱包余额支付
			handleWalletPay() {
				this.handlePayResult({
					result: PaymentStatusEnum['SUCCESS'],
					order_id: this.old_order_id
				});
			},
			handleTtPay(data) {
				return new Promise((resolve, reject) => {
					ttpay(data)
						.then(async (res) => {
							resolve(res)
						})
						.catch(errMsg => reject(errMsg))
				})
			},

			// 通联支付支付
			handleTongLianPay(data) {
				return new Promise((resolve, reject) => {
					tonglianpay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},

			// E易收支付支付
			handleEEasyPay(data) {
				return new Promise((resolve, reject) => {
					eeasypay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},
			// 厚联支付支付
			handleHouLianPay(data) {
				return new Promise((resolve, reject) => {
					houlianpay(data)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult().then(result => {
									result ? resolve(res) : reject(res)
								}).catch(errMsg => reject(errMsg))
							})
							// #endif
						})
						.catch(errMsg => reject(errMsg))
				})
			},

			// 查询支付结果
			queryPayResult() {
				return new Promise((resolve, reject) => {
					apiPayStatus({
						from: "order",
						order_id: this.old_order_id,
					}).then(({
						pay_status
					}) => {
						resolve(pay_status == 1 ? true : false)
					}).catch(errMsg => reject(errMsg))
				})
			},
			// 处理：微信订阅消息
			handleSubscribeMP_WEIXIN() {
				let that = this
				return new Promise((resolve, reject) => {
					apiSubscribe().then(data => {
						if (!data.length) reject(that.$zhTran('暂无可订阅信息'))
						uni.requestSubscribeMessage({
							tmplIds: data,
							success(res) {
								resolve(res)
							},
							fail(err) {
								reject(that.$zhTran('订阅失败'))
							},
						})
					}).catch(() => reject(that.$zhTran('订阅获取失败')))
				})
			},

			// 下单处理
			handlePlaceOrder() {
				// 阻止重复操作
				if (this.loadingPay) return
				this.loadingPay = true

				return new Promise((resolve, reject) => {
					apiOrderPlace({
							...this.orderFormParams,
							...this.pageQueryPayload,
							...this.orderExtendParams,
							rr_share_id: this.options.rr_share_id || '',
							rra_id: this.options.rra_id || '',
							action: 'buy',
						}).then(data => {
							// 监听全局duringPayment事件
							uni.$once('duringPayment', data => {
								this.handlePayResult(data)
							})

							return data
						}).then(({
							type,
							order_id,
							order_audit_pass,
							goods_disabled
						}) => {
							if (goods_disabled != undefined && goods_disabled.length > 0) {
								this.goods_disabled = goods_disabled
								this.showInvalidGoods = true
							} else {
								if (order_audit_pass) {
									this.$Router.replace({
										path: '/bundle2/pages/payment_result/payment_result',
										query: {
											order_id,
											auditfrom: 1,
											from: 'order'
										}
									})
								} else {
									// 去支付
									this.$Router.replace({
										path: `/bundle2/pages/payment/payment`,
										query: {
											from: type,
											order_id,
										}
									})
								}
							}

							resolve(order_id)
						}).catch(errMsg => reject(errMsg))
						.finally(() => {
							this.loadingPay = false
						})
				})
			},

			// 支付结果处理
			handlePayResult({
				result,
				order_id
			}) {
				switch (result) {
					case PaymentStatusEnum['SUCCESS']:
					case PaymentStatusEnum['FAIL']:
						this.$Router.replace({
							path: '/bundle2/pages/payment_result/payment_result',
							query: {
								order_id,
								from: 'order'
							}
						})
						break
					case PaymentStatusEnum['CLOSE']:
						this.$Router.push({
							path: '/bundle2/pages/payment_result/payment_result',
							query: {
								order_id,
								from: 'order'
							}
						})
						break
				}
			},
			checkQuicklyPayStatus() {
				return new Promise((resolve, reject) => {
					apiQuicklyPayStatus({
						order_id: this.new_order_id
					}).then(function() {
						resolve(true);
					}).catch(function(e) {
						return reject(e);
					});
				});
			},
			async loadFunction() {
				// 初始化页面
				try {
					// 初始化页面参数
					this.from = this.options.from
					this.pageQueryPayload = this.options.payload

					// 初始化配送方式
					await this.initDeliveryType()
					// 初始化页面数据
					await this.initOrderData()
					this.integrateFlag && this.initPageData();

					// 初始化优惠券数据(营销商品不可使用)
					!this.isMarketing && !this.integrateFlag && await this.initCouponGoods()

					this.pageStatus = PageStatusEnum['NORMAL']
				} catch (errMsg) {
					this.pageErrorMsg = errMsg
					this.pageStatus = PageStatusEnum['ERROR']
					console.log('页面数据初始化失败', errMsg)
				}
			},
			async onUnloadFunction() {
				if (this.integrateFlag) {
					this.checkQuicklyPayStatus()
				}
				setTimeout(() => {
					this.eventChannel.emit("reCountCarNum", {});
				}, 500);
			},
			getUserInvoice() {
				apiUserIncoiceLists({
					page_type: 0,
				}).then(({
					lists,
					page_size,
					count,
					extend
				}) => {
					this.titleList = lists
				})
			},
			// 监听发票抬头选择切换事件
			invoiceChange(val) {
				if (this.timer) {
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					this.showInvoicePop = false
				}, 200);

			},
			// 新建发票
			addNewTitle() {
				this.$Router.push({
					path: '/bundle3/pages/invoice/add_invoice',
					query: {
						source: 'order',
					}
				})
			},
			invoiceTitleEdit(id) {
				this.$Router.push({
					path: "/bundle3/pages/invoice/add_invoice",
					query: {
						id,
						source: 'order',
					}
				})
			},
			toCart() {
				this.$Router.replace({
					path: '/bundle2/pages/shop_cart/shop_cart',
				})
			},
			// 不使用发票
			unUseInvoice() {
				this.orderForm.invoice_id = ''
				this.showInvoicePop = false
			},
		},
		onLoad() {
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}
			// const options = this.$Route.query
			const eventChannel = this.getOpenerEventChannel()
			this.eventChannel = eventChannel
			eventChannel.on("receiveData", (data) => {
				this.options = this.$zhTran(data)
				console.log('options', data)
				this.loadFunction();
			});
		},

		onShow() {
			// #ifdef H5
			this.$emit('h5_payment')
			// #endif

			// #ifndef H5
			let options = wx.getEnterOptionsSync();
			if (options.scene == '1038' && options.referrerInfo.appId == this.pay_appid) {
				// 代表从收银台小程序返回
				let extraData = options.referrerInfo.extraData;
				if (!extraData) {
					// "当前通过物理按键返回，未接收到返参，建议自行查询交易结果";
					this.queryPayResult().then(result => {
						result ? this.handlePayResult(PaymentStatusEnum['SUCCESS']) : this.handlePayResult(
							PaymentStatusEnum['FAIL'])
					}).catch(errMsg => this.handlePayResult(errMsg))
				} else {
					if (extraData.code == 'success') {
						// "支付成功";
						this.handlePayResult(PaymentStatusEnum['SUCCESS'])
					} else if (extraData.code == 'cancel') {
						// "支付已取消";
						this.handlePayResult(PaymentStatusEnum['FAIL'])
						console.log('PAYMENT_ERROR_MSG:', errMsg)
					} else {
						// "支付失败：" + extraData.errmsg;
						this.handlePayResult(extraData.errmsg)
						console.log('PAYMENT_ERROR_MSG:', extraData.errmsg)
					}
				}
			}
			// #endif

			this.getUserInvoice()
		},

		onUnload() {

			this.onUnloadFunction()

			uni.$off([
				'changeStore',
				'changeAddress',
			])
		}

	}
</script>

<style lang="scss" scoped>
	// Page style
	.goods-order {
		padding: 0 20rpx calc(100rpx + 20rpx + constant(safe-area-inset-bottom)) 20rpx;
		padding: 0 20rpx calc(100rpx + 20rpx + env(safe-area-inset-bottom)) 20rpx;

		// 卡片
		.contain {
			margin-top: 20rpx;
			border-radius: 7px;
			background-color: #FFFFFF;
			overflow: hidden;
		}

		// 单元格
		.cell {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: $-font-size-nr;
			color: $-color-black;

			&-label {
				width: 130rpx;
			}

			&-content {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: flex-end;
			}
		}

		// 初始化复选框的外边距
		.u-checkbox {
			::v-deep .u-checkbox__label {
				margin: 0;
			}
		}
	}

	// 配送方式
	.delivery {
		&-tabs {
			border-bottom: $-solid-border;
		}

		&-contain {
			// border-top: $-solid-border;
		}
	}

	// 门店自提表单
	.store-from {
		padding-left: 20rpx;
		font-size: $-font-size-nr;

		&-item {
			display: flex;
			align-items: center;
			height: 100rpx;
			padding-right: 20rpx;

			&:nth-child(n+2) {
				border-top: $-dashed-border;
			}
		}
	}

	// 商品
	.goods {

		&-item {
			position: relative;

			&:nth-child(n+2)::before {
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				display: block;
				content: "";
				border-top: $-solid-border;
				margin-left: 20rpx;
			}

			&-widget {
				padding: 0 20rpx 0 calc((20rpx * 2) + 160rpx);

				.delivery-tag {
					display: inline-block;
					padding: 4rpx 15rpx;
					margin-bottom: 20rpx;
					border-radius: 60px;
					font-size: $-font-size-xxs;
					background-color: #F4F4F4;
					color: $-color-muted;
				}
			}
		}

		// 会员价
		.vip-price {
			margin-top: 5rpx;
			background-color: #FFE9BA;
			color: #FFD4B7;
			line-height: 36rpx;
			border-radius: 6rpx;
			overflow: hidden;

			.price-name {
				background-color: #101010;
				padding: 3rpx 12rpx;
				position: relative;
				overflow: hidden;

				&::after {
					content: '';
					display: block;
					width: 20rpx;
					height: 20rpx;
					position: absolute;
					right: -15rpx;
					background-color: #FFE9BA;
					border-radius: 50%;
					top: 50%;
					transform: translateY(-50%);
					box-sizing: border-box;
				}
			}
		}
	}

	// 留言
	.remark {
		height: 100rpx;
		padding: 0 20rpx;
	}

	// 优惠
	.discounts {
		padding-left: 20rpx;

		&-item {
			height: 100rpx;
			padding-right: 20rpx;

			&:nth-child(n+2) {
				border-top: $-dashed-border;
			}
		}
	}

	// 订单清算
	.clearing {
		padding: 20rpx;

		&-item {
			height: 70rpx;
		}
	}

	// 订单功能区
	.operational {
		box-sizing: border-box;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 100;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx constant(safe-area-inset-bottom) 20rpx;
		padding: 0 20rpx env(safe-area-inset-bottom) 20rpx;
		border-top: $-solid-border;
		background-color: #FFFFFF;

		.order-amount {
			font-size: &-font-size-nr;
			color: $-color-normal;
		}

		&-button {
			padding: 16rpx 45rpx;
			border-radius: 60px;
			font-size: $-font-size-md;
			@include background_linear() color: #FFFFFF;
		}
	}

	// 优惠券【弹窗】
	.coupons {
		background-color: #f6f6f6;

		&-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 100rpx;
			padding: 0 30rpx;
			font-weight: 500;
			font-size: $-font-size-md;
			background-color: #FFFFFF;
		}

		&-main {
			&__tabs {
				border-top: $-solid-border;
			}

			&__contain {
				// margin-top: 20rpx;
				padding: 0 20rpx;
			}

			.coupons-item {
				margin-top: 20rpx;
			}
		}

		&-footer {
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			height: 100rpx;
			background-color: #FFFFFF;

			&-button {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				height: 82rpx;
				border-radius: 60px;
				font-size: $-font-size-lg;
				@include background_color();
				color: #FFFFFF;
			}
		}
	}

	.gfa-tag {
		width: 80rpx;
		height: 40rpx;
		border: 1rpx solid red;
		border-radius: 6rpx;
		color: red;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.payment-main {

		.payway-container {
			padding: 0 20rpx;
			border-radius: 7px;
			background-color: #FFFFFF;

			.payway-empty {
				display: flex;
				justify-content: center;
				padding: 20rpx 0;
				font-size: $-font-size-sm;
				color: $-color-muted;
			}
		}

		.payway {
			width: 100%;

			&-item {
				width: 100%;
				display: flex;
				align-items: center;
				height: 120rpx;

				&:nth-child(n+2) {
					border-top: $-dashed-border;
				}

				&-content {
					flex: 1;
					display: flex;
					flex-direction: column;
					margin-left: 16rpx;

					&-name {
						font-size: $-font-size-nr;
						color: $-color-black;
					}

					&-tips {
						font-size: $-font-size-xxs;
						color: $-color-muted;
					}
				}
			}
		}
	}

	.invoice-title-container {
		height: 300px;
		background: #f5f5f5;
		padding-top: 10px;
	}

	.pop-container {
		background: #f5f5f5;

		.pop-header {
			display: flex;
			justify-content: center;
			align-items: center;
			padding-top: 10px;
			color: #333333;
			font-size: 16px;
			font-weight: 400;
			background: #f5f5f5;
		}


		.footer-panel {
			margin: 25px 10px;

			.btn {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 42px;
				width: 100%;
				color: #ffffff;
				font-size: 14px;
				font-weight: 400;
				margin-bottom: 11px;
				border-radius: 800px;

				&.cancel {
					border: 1px solid #eee;
				}
			}
		}

		.container {
			flex: 1;
		}

		.invoice-title-panel {
			width: calc(100% - 20px);
			margin: 10px;
			padding: 16px 17px 13px 16px;
			background: #fff;
			border-radius: 5px;
			display: flex;
			align-items: center;

			.upper-panel {
				align-items: center;
				justify-content: space-between;

				.title-name {
					align-items: center;

					text {
						font-size: 14px;
						font-weight: 700;
						color: #333333;
					}

					.default-tag {
						width: 27px;
						height: 13px;
						display: flex;
						align-items: center;
						justify-content: center;
						color: #D43030;
						font-size: 10px;
						text-align: center;
						border: 0.8px solid #D43030;
						margin-left: 3px;
					}

				}

				.type-tag {
					padding: 0 15rpx;
					height: 21px;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 11px;
					background: #FFF7E6;
					color: #D69027;

					&.enterprise {
						background: #FEEDF0;
						color: #D43030;
					}

				}

			}

			.main-panel {
				display: flex;
				justify-content: space-between;
				align-items: flex-end;
			}

			.title-info {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				margin-top: 6px;

				.mailbox,
				.mobile {
					font-size: 12px;
					font-weight: 400;
					color: #666666;
					margin-bottom: 5px;
				}
			}

			.footer-panel {
				display: flex;
				justify-content: flex-end;
				align-items: center;
			}

			.btn {
				display: flex;
				align-items: center;
				font-size: 12px;
				font-weight: 400;
				color: #333333;

				&:first-child {
					margin-right: 20px;
				}

				.icon {
					width: 10px;
					height: 10px;
				}
			}

		}
	}

	.invalid-container {
		overflow: hidden;
		padding: 20rpx 0;

		.pop-header {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 10px 0;
			color: #333333;
			font-size: 16px;
			font-weight: 400;
		}

		.footer-panel {
			padding: 0 20rpx;
		}

		.btn {
			padding: 20rpx 0;
			font-size: 24rpx;
			color: #fff;
			background-color: rgba(255, 44, 60, 1);
			border-radius: 50rpx;
		}
	}
</style>